<?php

	$page_name=basename($_SERVER['SCRIPT_FILENAME']);
	
	include("general_include.php");
	
	if (empty($_GET['action'])) $_GET['action'] = 'process';
	
	if ($_GET['action'] <> 'ipn') include "checklogin.php";
	
	require_once('paypal.class.php');  // include the class file
	include_once('transaction_status.class.php');
	
	$p = new paypal_class;             // initiate an instance of the class
	$p->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';   // testing paypal url
	//$p->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';     // paypal url
	
	$p->test_enable = true;
	// By default is disable, here it is being activated.

	// setup a variable for this script (ie: 'http://www.micahcarrick.com/paypal.php')
	$this_script = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
	$cashier = 'http://'. $_SERVER['HTTP_HOST'] .'/newsite/cashier.php';

	// if there is not action variable, set the default action of 'process'
	if (empty($_GET['action'])) $_GET['action'] = 'process';  
	
	switch ($_GET['action']) {
		
		case 'process':      // Process and order...

			// There should be no output at this point.  To process the POST data,
			// the submit_paypal_post() function will output all the HTML tags which
			// contains a FORM which is submited instantaneously using the BODY onload
			// attribute.  In other words, don't echo or printf anything when you're
			// going to be calling the submit_paypal_post() function.
				 
			// This is where you would have your form validation  and all that jazz.
			// You would take your POST vars and load them into the class like below,
			// only using the POST values instead of constant string expressions.
				 
			// For example, after ensureing all the POST variables from your custom
			// order form are valid, you might have:
			//
			// $p->add_field('first_name', $_POST['first_name']);
			// $p->add_field('last_name', $_POST['last_name']);
			
			if (isset($_POST['id']) || isset($_GET['id'])) {
				// Transaction ID
				$txDate = date("d/m/Y : H:i:s", time());
				
				$txId = md5($_SESSION['user_id'].$txDate);
				
				$ratePointId = isset($_POST['id']) ? $_POST['id'] : $_GET['id'];

				$sqlQuery = "INSERT INTO ". TABLEPREFIX ."_user_transaction(nk_user_id, tx_date, rate_point_id, status, nk_tx_id) VALUES(". $_SESSION['user_id'] .", STR_TO_DATE('". $txDate ."', '%d/%m/%Y : %H:%i:%s'),". $ratePointId .", ". TransactionStatus::WAITING_CONF .",'". $txId ."')";
				$UserManagerObjAjax->Execute($sqlQuery);

				if(!mysql_error()) {

					$sqlQuery = "SELECT * FROM ". TABLEPREFIX ."_rate_points WHERE rate_point_id=". $ratePointId;
					$record = $UserManagerObjAjax->GetRecords("Row",$sqlQuery);
					
					$p->add_field('business', 'nskool_1340123167_biz@gmail.com');
					$p->add_field('return', $this_script.'?action=success');
					$p->add_field('cancel_return', $this_script.'?action=cancel&custom='.$txId);
					$p->add_field('notify_url', $this_script.'?action=ipn');
					$p->add_field('undefined_quantity', '1');
					$p->add_field('item_name', $record['description']);
					$p->add_field('amount', $record['rate']);
					$p->add_field('custom', $txId);

					$p->submit_paypal_post(); // submit the fields to paypal
				}
			}
			//$p->dump_fields();      // for debugging, output a table of all the fields
		break;

		case 'success':      // Order was successful...

			// This is where you would probably want to thank the user for their order
			// or what have you.  The order information at this point is in POST 
			// variables.  However, you don't want to "process" the order until you
			// get validation from the IPN.  That's where you would have the code to
			// email an admin, update the database with payment status, activate a
			// membership, etc.  
				
			echo 	"<html>
						<head>
							<title>Success</title>
							<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=". $cashier."?txStatus=1&txMsg=The%20transaction%20has%20succeeded.%20Waiting%20for%20the%20PayPal%20notification.\">
						</head>
					</html>";
			//foreach ($_POST as $key => $value) { echo "$key: $value<br>"; } This is the information from PayPal
			
			// You could also simply re-direct them to another page, or your own 
			// order status page which presents the user with the status of their
			// order based on a database (which can be modified with the IPN code 
			// below).

		break;

		case 'cancel':       // Order was canceled...
		
			$addSelect = "SELECT * ";
			$addDelete = "DELETE ";
			
			$txId = $_GET['custom'];
			
			$restQuery = " FROM ". TABLEPREFIX ."_user_transaction WHERE nk_tx_id='". $txId ."' AND status = ". TransactionStatus::WAITING_CONF;
		
			$sqlQuery = $addSelect . $restQuery;
			$record = $UserManagerObjAjax->GetRecords("Row",$sqlQuery);
			if (sizeof($record) > 0) {
				$sqlQuery = $addDelete . $restQuery;
				$UserManagerObjAjax->Execute($sqlQuery);
				$plusUrl="?txStatus=2&txMsg=The order was canceled.";
				$cashier = $cashier . $plusUrl;
			}
			// The order was canceled before being completed.
			echo 	"<html>
						<head>
							<title>Success</title>
							<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=". $cashier."\">
						</head>
					</html>";

		break;

		case 'ipn':          // Paypal is calling page for IPN validation...

			// It's important to remember that paypal calling this script.  There
			// is no output here.  This is where you validate the IPN data and if it's
			// valid, update your database to signify that the user has payed.  If
			// you try and use an echo or printf function here it's not going to do you
			// a bit of good.  This is on the "backend".  That is why, by default, the
			// class logs all IPN data to a text file.
			if ($p->validate_ipn()) {
				
				// Payment has been recieved and IPN is verified.  This is where you
				// update your database to activate or process the order, or setup
				// the database with the user's order details, email an administrator,
				// etc.  You can access a slew of information via the ipn_data() array.
				
				// Check the paypal documentation for specifics on what information
				// is available in the IPN POST variables.  Basically, all the POST vars
				// which paypal sends, which we send back for validation, are now stored
				// in the ipn_data() array.
				
				$qtyBought	=	$p->ipn_data['quantity'];
				$txId		=	$p->ipn_data['custom'];
				$payPalAcct	=	$p->ipn_data['address_name'];
				
				$sqlQuery = "SELECT nk_user_id, tx_date, DATE_FORMAT(tx_date , '%d/%m/%Y : %H:%i:%s') AS formated_tx_date, nk_tx_id, rate_point_id FROM ". TABLEPREFIX ."_user_transaction WHERE nk_tx_id='". $txId ."' AND status = ". TransactionStatus::WAITING_CONF;
				$record = $UserManagerObjAjax->GetRecords("Row",$sqlQuery);
				
				$serverTxDate			=	$record['tx_date'];
				$txDate			=	$record['formated_tx_date'];
				$nkUserId		=	$record['nk_user_id'];
				$ratePointId	=	$record['rate_point_id'];
				
				if (sizeof($record) > 0 && md5($nkUserId.$txDate)==$txId) {
					// For this example, we'll just email ourselves ALL the data.
					
					$sqlQuery = "UPDATE ". TABLEPREFIX ."_user_transaction SET status = ". TransactionStatus::ACTIVE .", qty_points = '". $qtyBought ."' WHERE nk_tx_id='". $txId ."' AND status = ". TransactionStatus::WAITING_CONF;
					$UserManagerObjAjax->Execute($sqlQuery);
					
					$sqlQuery = "SELECT * FROM ". TABLEPREFIX ."_rate_points WHERE rate_point_id=". $ratePointId;
					$record = $UserManagerObjAjax->GetRecords("Row",$sqlQuery);
					
					$rateDescription = $record['description'];
					$totalPoints = $record['qty_points']*$qtyBought;
					$totalCharged = $record['rate']*$qtyBought;
					
					$sqlQuery = "UPDATE ". TABLEPREFIX ."_user SET total_points=". $totalPoints ."+total_points WHERE user_id=". $nkUserId;
					$UserManagerObjAjax->Execute($sqlQuery);
					
					$sqlQuery = "SELECT * FROM ". TABLEPREFIX ."_user WHERE user_id=". $nkUserId;
					$record = $UserManagerObjAjax->GetRecords("Row",$sqlQuery);
					$userEmail = $record['email'];
					
					$subject = 'Payment Notification - '.$rateDescription;
					$to = $userEmail;    //  User email
					$body =  "Your transaction has succesfully ended.\nDetails below:\n";
					$body .= "\nNo Transaction: ". $txId;
					$body .= "\nServer Transaction Date: ". $serverTxDate;
					$body .= "\nQuantity bought: ". $qtyBought;
					$body .= "\nTotal points added: ". $totalPoints;
					$body .= "\nTotal charged: ". $totalCharged;
					
					$p->log_action("Mail to:   ". $userEmail ."\n". $body);
					mail($to, $subject, $body);
				}
				
			}
		break;
	}     

?>